/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.weso.acota.strategy;

import java.util.LinkedList;
import java.util.List;
import org.weso.acota.dao.SuggestDAO;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.to.TagTO;

/**
 *
 * @author chema
 */
public class MapReduceCotaCollectStrategy implements CotaCollectStrategy{

    List<TagTO> tags = new LinkedList<TagTO>();

    @Override
    public SuggestionTO suggest(RequestSuggestionTO request, List<SuggestDAO> sources) {
        SuggestionTO result = new SuggestionTO();
        for (SuggestDAO suggestDAO : sources) {
            new StartThread(request, suggestDAO).start();
        }
        //FIXME: No se sincroniza así!!!
        try {
            Thread.currentThread().sleep(1000);
        } catch (Exception e) {
        }

        //Reduce sería la estrategia de ordenación
        result.setTags(tags);
        return result;
    }

    

    class StartThread extends Thread {

        private SuggestDAO suggestDAO;
        private RequestSuggestionTO request;
        
        public StartThread(RequestSuggestionTO request, SuggestDAO suggestDAO) {
            this.suggestDAO = suggestDAO;
            this.request = request;

        }

        public void run() {
                SuggestionTO suggest = suggestDAO.suggest(request);
                synchronized (this) {
                    tags.addAll(suggest.getTags());
                }
            }
        }
}
